<template>
    <el-card>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>内容管理</el-breadcrumb-item>
            <el-breadcrumb-item>文章/视频列表</el-breadcrumb-item>
        </el-breadcrumb>


        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="文章列表" name="first"></el-tab-pane>
            <el-tab-pane label="视频列表" name="sec"></el-tab-pane>
        </el-tabs>
        <div class="btnBox">
            <el-button @click="openAddArticleDialog('add', '')" size='small'>添加</el-button>
            <el-button @click="updateTopic(1)" size='small'>启用</el-button>
            <el-button @click="updateTopic(0)" size='small'>停用</el-button>
            <el-button @click="updateTopic(2)" size='small'>删除</el-button>
            <!-- /按钮区 -->
            <div>

                <el-input placeholder="请输入标题" size='small' v-model="topicTitle" @clear="getList" style="width: 243px;"
                    class="input-with-select" clearable>
                    <el-button slot="append" @click="getList" icon="el-icon-search"></el-button>
                </el-input>
            </div>
        </div>

        <!-- 数据展示 -->
        <el-table :data="articleListData" height="70vh" @selection-change="selectionChange"
            :header-cell-style="{ background: '#409EFF', color: '#FFF' }" style="width: 100%;margin-top:10px;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="topicId" width="100" label="文章编号"></el-table-column>
            <el-table-column prop="topicTitle" show-overflow-tooltip label="题目"></el-table-column>
            <el-table-column prop="topicAuth" show-overflow-tooltip label="作者"></el-table-column>

            <el-table-column prop="topicDate" label="发布时间" width="170"></el-table-column>
            <el-table-column prop="topicOrder" label="排序" width="170"></el-table-column>


            <el-table-column label="状态" width="80">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.topicStatus == 1">启用</el-tag>
                    <el-tag v-if="scope.row.topicStatus == 0" type="warning">已下架</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="封面">
                <template slot-scope="prop">
                    <el-image style="width: 100px; height: 100px; border-radius:8px;" fit="cover"
                        :preview-src-list="[baseurl + 'zhonghui/topic/' + prop.row.topicCover]"
                        :src="baseurl + 'zhonghui/topic/' + prop.row.topicCover"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="内容">
                <template slot-scope="prop">
                    <el-image style="width: 100px; height: 100px; border-radius:8px;" fit="cover"
                        v-if="prop.row.topicFlag == 0"
                        :preview-src-list="[baseurl + 'zhonghui/topicCoverpic/' + prop.row.topicContent]"
                        :src="baseurl + 'zhonghui/topicCoverpic/' + prop.row.topicContent"></el-image>

                    <video :src="baseurl + 'zhonghui/topicCoverpic/' + prop.row.topicContent" v-else class="videoBox"
                        controls></video>

                </template>
            </el-table-column>
            <el-table-column label="标签">
                <template slot-scope="prop">{{ prop.row.tagIds | getTagStr }}</template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="prop">
                    <el-button @click="openAddArticleDialog('edit', prop.row)" size="small">修改</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNow"
            :page-sizes="[50, 100, 200]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"></el-pagination>


        <!-- 添加/修改文章弹窗 -->
        <el-dialog :title="form.flag == 'add' ? '添加' : '修改'" :visible.sync="addArticleDialog" width="600px"
            :close-on-click-modal="false">
            <div>
                <el-form :inline="true" ref="formRef" :rules="rules" :model="form">
                    <el-form-item label="主标题" prop="topicTitle">
                        <el-input v-model="form.topicTitle" size="small" style="width:200px;"
                            placeholder="请输入主标题"></el-input>
                    </el-form-item>

                    <el-form-item label="作者" prop="topicAuth">
                        <el-input v-model="form.topicAuth" size="small" style="width:200px;"
                            placeholder="请输入作者"></el-input>
                    </el-form-item>

                    <br />

                    <el-form-item label="排序" prop="topicOrder">
                        <el-input type="number" v-model="form.topicOrder" size="small" style="width:200px;"
                            placeholder="请输入排序值"></el-input>
                        <div class="sortTip">tips：数值越大，在列表中越靠前，最小数值为1</div>
                    </el-form-item>

                    <el-form-item label="发布时间" prop="topicDate">
                        <el-date-picker v-model="form.topicDate" size="small" style="width:204px;"
                            value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择"></el-date-picker>
                    </el-form-item>

                    <el-form-item label="状态" prop="topicStatus">
                        <el-select v-model="form.topicStatus" size="small" style="width:200px;" placeholder="请选择">
                            <el-option label="启用" value="1"></el-option>
                            <el-option label="禁用" value="0"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="内容标签" prop="tagIds">
                        <el-select v-model="form.tagIds" size="small" style="width:200px;" placeholder="请选择" multiple>
                            <el-option v-for=" item  in  tagList " :key="item.tagId" :label="item.tagName"
                                :value="item.tagId"></el-option>
                        </el-select>
                        <!-- <el-button style="margin-left: 16px;" @click="addPreparer">新增</el-button> -->
                    </el-form-item>
                    <br />
                    <el-form-item label="封面" style="margin-top:8px;">
                        <img class="imgBox" v-if="form.flag == 'edit' && form.topicCover != ''"
                            :src="baseurl + 'zhonghui/topic/' + form.topicCover" alt="">

                        <el-upload ref="loadRef1" action="a" :on-change="fmHandleChange" :on-remove="fmHandleRemove"
                            :limit="1" :file-list="fileList1" :auto-upload="false" accept="image/*" list-type="picture">
                            <el-button size="small" type="primary" style="width:90px">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                    <br />
                    <el-form-item label="内容" style="margin-top:8px;">

                        <template v-if="form.flag == 'edit' && form.topicContent != ''">
                            <img class="imgBox" v-if="form.topicFlag == 0"
                                :src="baseurl + 'zhonghui/topicCoverpic/' + form.topicContent" alt="">
                            <video :src="baseurl + 'zhonghui/topicCoverpic/' + form.topicContent" v-else
                                class="videoBox" controls></video>
                        </template>

                        <el-upload action="a" :on-change="handleChange" :on-remove="handleRemove" :file-list="fileList"
                            :auto-upload="false" :accept="form.topicFlag == 0 ? 'image/*' : 'video/*'"
                            :list-type="form.topicFlag == 0 ? 'picture' : ''" ref="loadRef">
                            <el-button size="small" type="primary" style="width:90px">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">*注：请上传{{ form.topicFlag == 0 ? '图片' : '视频' }} </div>
                        </el-upload>
                    </el-form-item>

                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddArticleDialog">取 消</el-button>
                <el-button type="primary" @click="submitHandle">确 定</el-button>
            </span>
        </el-dialog>
        <!-- /添加/修改文章弹窗 -->



    </el-card>
</template>

<script>


import { url } from '../../network/request'
import { addTopic, getTopicPage, updateTopic, deleteTopic, getTagList } from '../../network/content'
let that
export default {
    data() {
        return {
            baseurl: url,
            activeName: 'first',
            form: {
                flag: 'add',
                topicId: '',
                topicTitle: '',
                topicAuth: '',
                topicDate: '',
                topicStatus: '1',  //  0 禁用   1 启用
                topicFlag: 0,// 0 文章    1 视频 
                topicOrder: '',//排序
                shopId: sessionStorage.shop_id,
                tagIds: '', // 关联标签 
                topicCover: '',
                topicContent: '',
                tagIds: '',
            },
            addArticleDialog: false,

            fmFile: '',
            mainFile: '',

            rules: {
                topicTitle: [{ required: true, message: "请输入主标题", trigger: "blur" }],
                topicAuth: [{ required: true, message: "请输入作者", trigger: "blur" }],
                topicDate: [{ required: true, message: "请选择发布时间", trigger: "change" }],
                topicOrder: [{ required: true, message: "请输入排序值", trigger: "blur" }],
                tagIds: [{ required: true, message: "请选择关联标签", trigger: "change" }],
                topicStatus: [{ required: true, message: "请选择状态", trigger: "change" }],
            },

            tagList: [
                {
                    tagId: 1,
                    tagName: '健康科普'
                },
                {
                    tagId: 2,
                    tagName: '科普'
                },
            ],
            checkList: [],
            topicTitle: '',//搜索关键词

            pageNow: 1,
            pageSize: 50,
            totalCount: 0,
            articleListData: [],
            fileList1: [],
            fileList: [],
        };
    },
    methods: {
        getData() {
            getTagList().then(res => {
                if (res.flag) {
                    this.tagList = res.data.reverse()
                }
            })
        },

        getList() {

            getTopicPage({
                page: this.pageNow,
                size: this.pageSize,
                topicFlag: this.form.topicFlag,
                topicTitle: this.topicTitle
            }).then(res => {
                if (res.flag) {
                    console.log(res.data);
                    this.articleListData = res.data.list
                    this.totalCount = res.data.total
                }
            })

        },
        updateTopic(status) {
            //修改 删除文章 
            if (this.checkList.length === 0)
                return this.$message.warning("请选择要操作的数据");
            let ids = "";
            for (var i = 0; i < this.checkList.length; i++) {
                ids = ids + this.checkList[i].topicId + ",";
            }
            if (status == 2) {
                deleteTopic({
                    ids,
                }).then(res => {
                    if (res.flag) {
                        this.getList();
                        this.$message.success("删除成功");
                    } else {
                        this.$message.error("删除失败");
                    }
                })
            }
            updateTopic({
                ids,
                topicStatus: status,
            }).then(res => {
                console.log(res);
                if (res.flag) {
                    this.getList();
                    this.$message.success("状态更新成功");
                } else {
                    this.$message.error("状态更新失败");
                }
            });
        },
        selectionChange(val) {
            this.checkList = val;
            console.log(this.checkList);
            console.log(val);

        },

        openAddArticleDialog(str, obj) {
            console.log(obj);

            if (str == 'edit') {
                this.form = JSON.parse(JSON.stringify(obj))
                this.form.topicStatus = obj.topicStatus + ''

                if (this.form.tagIds != null) {
                    var arr = this.form.tagIds.split(',')

                    console.log(arr);

                    this.form.tagIds = []
                    arr.forEach(ele => {
                        this.form.tagIds.push(Number(ele))
                    })
                } else {
                    this.form.tagIds = []
                }

            }
            this.form.flag = str

            console.log(this.form);
            console.log(obj);
            this.addArticleDialog = true
        },


        // 确认
        submitHandle() {

            this.$refs.formRef.validate(valid => {
                if (valid) {

                    console.log(this.form);


                    if (this.form.flag == 'add' && this.fmFile == '') {
                        this.$message.warning('请上传封面图')
                        return
                    }
                    if (this.form.flag == 'add' && this.mainFile == '') {
                        this.$message.warning('请上传内容')
                        return
                    }
                    if (this.form.topicCover == '' && this.fmFile == '') {
                        this.$message.warning('请上传封面图')
                        return
                    }
                    if (this.form.topicContent == '' && this.mainFile == '') {
                        this.$message.warning('请上传内容')
                        return
                    }

                    console.log(this.fmFile);
                    console.log(this.mainFile);


                    // return


                    let fd = new FormData();


                    if (this.form.flag == 'edit') {
                        fd.append('topicId', this.form.topicId)

                        if (this.form.topicCover == '') {
                            fd.append("topic", this.fmFile);
                        } else {
                            fd.append("topic", this.form.topicCover);
                        }

                        if (this.form.topicContent == '') {
                            fd.append("topicCoverpic", this.mainFile);
                        } else {
                            fd.append("topicCoverpic", this.form.topicContent);
                        }
                    } else {
                        fd.append("topic", this.fmFile);
                        fd.append("topicCoverpic", this.mainFile);
                    }


                    fd.append("topicTitle", this.form.topicTitle);
                    fd.append("shopId", this.form.shopId);
                    fd.append("topicAuth", this.form.topicAuth);
                    fd.append("topicDate", this.form.topicDate);
                    fd.append("topicStatus", this.form.topicStatus);
                    fd.append("topicFlag", this.form.topicFlag);
                    fd.append("topicOrder", this.form.topicOrder);
                    fd.append("flag", this.form.flag);


                    fd.append("tagIds", this.form.tagIds.join(','));
                    addTopic(fd).then(res => {
                        console.log(res);
                        if (res.flag) {
                            this.$message.success("发布成功");
                            this.getList();
                            this.$refs.formRef.resetFields();
                            this.closeAddArticleDialog();
                        } else {
                            this.$message.error("发布失败");
                        }
                    });

                } else {
                    return false;
                }
            });



        },


        // 内容图片
        handleChange(file, fileList) {

            this.mainFile = file.raw;
            if (this.form.flag == 'edit') {
                this.form.topicContent = ''
            }
        },
        handleRemove(file, fileList) {
            this.mainFile = "";
        },
        // 封面
        fmHandleChange(file, fileList1) {
            console.log(file);
            this.fmFile = file.raw;
            if (this.form.flag == 'edit') {
                this.form.topicCover = ''
            }
        },
        fmHandleRemove(file, fileList1) {
            this.fmFile = "";
        },
        handleClick() {
            console.log(this.activeName);
            this.form.topicFlag = this.activeName == 'first' ? 0 : 1
            this.pageNow = 1
            this.pageSize = 50
            this.getList()
        },

        closeAddArticleDialog() {
            this.addArticleDialog = false

            this.form = {
                flag: 'add',
                topicId: '',
                topicTitle: '',
                topicAuth: '',
                topicDate: '',
                topicStatus: 1,  //  0 禁用   1 启用
                topicFlag: 0,// 0 文章    1 视频 
                topicOrder: '',//排序
                shopId: sessionStorage.shop_id,
                tagIds: '', // 关联标签 
            }
            this.fmFile = ''
            this.mainFile = ''


            this.$refs.loadRef1.clearFiles()
            this.$refs.loadRef.clearFiles()

        },

        handleSizeChange(val) {
            this.pageSize = val;
            this.getList();
        },
        handleCurrentChange(val) {
            this.pageNow = val;
            this.getList();
        },

    },
    filters: {
        getTagStr(val) {
            console.log(val);
            var str = '';
            if (val) {
                val.split(',').forEach(item => {
                    that.tagList.forEach(ele => {
                        if (ele.tagId == item) {
                            str += ele.tagName + ' / '
                        }
                    })
                })
            }
            return str
        }
    },
    created() {
        this.getList()
        this.getData()
    },
    beforeCreate() {
        that = this
    }
};
</script>

<style scoped>
.el-card {
    position: relative;
}

.btnBox {
    margin-top: 0px;
    display: flex;
    align-items: center;
}

.btnBox>div {
    margin-left: 15px;
}

.el-upload__tip {
    color: blue;

}

.videoBox {
    width: 120px;
    height: 120px;
}

.imgBox {

    height: 120px;
    width: 120px;
}
</style>